package Pet.Management.common.exception;

import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleServiceException(ServiceException e) {
        logger.error("业务异常: {}", e.getMessage());
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("msg", e.getMessage());
        return result;
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("msg", e.getMessage());
        return result;
    }
    
    /**
     * JWT相关异常
     */
    @ExceptionHandler({io.jsonwebtoken.JwtException.class, io.jsonwebtoken.security.SecurityException.class})
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleJwtException(Exception e) {
        logger.error("JWT异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 401);
        result.put("msg", "token无效或已过期");
        return result;
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleException(Exception e) {
        logger.error("系统异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("msg", "系统错误，请联系管理员");
        return result;
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("参数验证异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        // 获取验证失败的第一个错误信息
        FieldError fieldError = e.getBindingResult().getFieldError();
        if (fieldError != null) {
            result.put("msg", fieldError.getDefaultMessage());
        } else {
            result.put("msg", "参数验证失败");
        }
        return result;
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public Map<String, Object> handleBindException(BindException e) {
        logger.error("绑定异常", e);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        // 获取验证失败的第一个错误信息
        FieldError fieldError = e.getBindingResult().getFieldError();
        if (fieldError != null) {
            result.put("msg", fieldError.getDefaultMessage());
        } else {
            result.put("msg", "参数验证失败");
        }
        return result;
    }
} 